package com.project.web.admin.utils.captcha;

import com.octo.captcha.Captcha;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.captchastore.CaptchaAndLocale;
import com.octo.captcha.service.captchastore.CaptchaStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.yun.common.utils.SpringUtils;
import org.yun.common.utils.redis.RedisClient;
import org.yun.common.utils.redis.RedisConsts;

import java.util.Collection;
import java.util.Locale;

/**
 * Created by Administrator on 2016/4/11.
 */
public class RedisCaptchaStore implements CaptchaStore {

    @Autowired
    private RedisClient redisClient;

    private RedisClient getRedisClient() {
        if (redisClient == null) {
            redisClient = (RedisClient) SpringUtils.getBean("redisClient");
        }
        return redisClient;
    }

    public boolean hasCaptcha(String id) {
        boolean flag = false;
        if (getRedisClient().get(id) != null) {
            flag = true;
        }
        return flag;
    }

    public void storeCaptcha(String id, Captcha captcha) throws CaptchaServiceException {
        getRedisClient().set(id, new CaptchaAndLocale(captcha));
    }

    public void storeCaptcha(String id, Captcha captcha, Locale locale) throws CaptchaServiceException {
        getRedisClient().setAndExpire(id, new CaptchaAndLocale(captcha), RedisConsts.ADMIN_CAPTCHA_EXPIRE);
    }

    public Locale getLocale(String id) throws CaptchaServiceException {
        Object captchaAndLocale = getRedisClient().get(id);
        return captchaAndLocale != null ? ((CaptchaAndLocale) captchaAndLocale).getLocale() : null;
    }

    public boolean removeCaptcha(String id) {
        if (getRedisClient().get(id) != null) {
            getRedisClient().del(id);
            return true;
        } else {
            return false;
        }
    }

    public Captcha getCaptcha(String s) throws CaptchaServiceException {
        CaptchaAndLocale captchaAndLocale = (CaptchaAndLocale) getRedisClient().get(s);
        return captchaAndLocale.getCaptcha();
    }

    public int getSize() {
        return getRedisClient().keys(RedisConsts.ADMIN_REDIS_CAPTCHA_KEY + "*").size();
    }

    public Collection getKeys() {
        return getRedisClient().keys(RedisConsts.ADMIN_REDIS_CAPTCHA_KEY + "*");
    }

    @Override
    public void empty() {

    }

}
